import React from 'react';
import {Breadcrumb, Icon, Popover} from 'antd';
import {WeaLocaleProvider, WeaTools} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

import './style';
import SearchRcmd from './SearchRcmd';

class PortalMenu extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [{
                module: '',
                name: props.type === 'top' ? getLabel(33676, '后端菜单') : getLabel(33675, '前端菜单'),
                data: []
            }],
            index: 0,
            rcmdVisible: false,
            rcmdData: []
        };
        this.setShowData = this.setShowData.bind(this);
        this.getShowData = this.getShowData.bind(this);
        this.onOpenMenu = this.onOpenMenu.bind(this);
        this.onRcmdSearch = this.onRcmdSearch.bind(this);
        this.onRcmdVisibleChange = this.onRcmdVisibleChange.bind(this);
    }

    componentWillMount() {
        const {type} = this.props;

        let api = '';
        if (type === 'top') {
            api = '/api/portal/menu/getBackEndMenu';
        } else if (type === 'left') {
            api = '/api/portal/menu/getFrontEndMenu?withPortal=0&isLoadAll=1';
        }

        api && WeaTools.callApi(api, 'GET', {}).then(result => {
            const {data = []} = result;
            this.setState({
                data: [{
                    module: '',
                    name: type === 'top' ? getLabel(33676, '后端菜单') : getLabel(33675, '前端菜单'),
                    data: data
                }],
                index: 0
            });
        });
    }

    render() {
        const {data, index, rcmdVisible, rcmdData} = this.state;

        return (
            <div className="em-portal-menu">
                <div className="em-portal-menu-toolbar">
                    <div className="em-portal-menu-back" title={getLabel(500304, '上一级')} onClick={() => this.getShowData(index - 1)}>
                        <img src="/spa/portal/images/em/back.png" alt=""/>
                    </div>
                    <div className="em-portal-menu-nav">
                        <Breadcrumb separator={<i className="icon-coms-organization-right"/>}>
                            {
                                data.map((item, index) => {
                                    return (
                                        <Breadcrumb.Item key={index} onClick={() => item.data && item.data.length && this.getShowData(index)}>
                                            {index === 0 && <Icon type="home"/>}
                                            <span>{item.name}</span>
                                        </Breadcrumb.Item>
                                    );
                                })
                            }
                        </Breadcrumb>
                    </div>
                    <div className="em-portal-menu-search">
                        <Popover
                            trigger="click"
                            placement="bottomLeft"
                            content={<SearchRcmd data={rcmdData} onOpenMenu={this.onOpenMenu}/>}
                            overlayClassName="em-portal-menu-search-rcmd"
                            visible={rcmdVisible}
                            onVisibleChange={this.onRcmdVisibleChange}
                        >
                            <div></div>
                        </Popover>
                        <input placeholder={getLabel(500305, '请输入菜单名称/首字母')} onClick={this.onRcmdSearch} onChange={this.onRcmdSearch}/>
                        <i className="icon-coms-search"/>
                    </div>
                </div>
                <div className="em-portal-menu-content">
                    <div id="contentMask" className="em-portal-menu-mask"></div>
                    <div className="em-portal-menu-main">
                        <div id="contentRoute" className="em-portal-menu-route">
                            {
                                this.props.children ? this.props.children : (
                                    <ul className="em-portal-menu-list">
                                        {
                                            data[index]['data'].map((item) => {
                                                let iconComp = null;
                                                if (item.icon) {
                                                    iconComp = <i className={item.icon}/>;
                                                } else {
                                                    if (index === 0) {
                                                        iconComp = <i className={`wevicon-top-menu-default wevicon-top-menu-${item.id}`}/>;
                                                    } else {
                                                        iconComp = <i className={`wevicon wevicon-menu-default wevicon-menu-${item.parentId}-${item.levelid}`}/>;
                                                    }
                                                }

                                                return (
                                                    <li key={item.id} onClick={() => this.setShowData(data[index]['module'], item, index + 1)}>
                                                        <div className={`em-portal-menu-item e9header-top-menu-color${(Math.abs(parseInt(item.id, 10)) & 7)}`}>
                                                            {iconComp}
                                                        </div>
                                                        <span>{item.name}</span>
                                                    </li>
                                                );
                                            })
                                        }
                                    </ul>
                                )
                            }
                        </div>
                        <div id="contentFrame" className="em-portal-menu-frame">
                            <iframe id="mainFrame" name="mainFrame" src="about:blank"></iframe>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    setShowData(module, item, index) {
        const {data} = this.state;
        data.push({module: module || item.id, parentId: item.parentId, id: item.id, name: item.name, data: item.child || []});
        this.setState({data, index});

        if (item) {
            this.onOpenMenu(item);
        }
    }

    getShowData(index) {
        if (index >= 0) {
            const {data} = this.state;
            this.setState({data: data.slice(0, index + 1), index});
            this.onOpenMenu({mobxrouteurl: '/main'});
        }
    }

    onOpenMenu(obj, from) {
        if (from === 'search') {
            const index = 0;
            const {data} = this.state;
            this.setState({data: data.slice(0, index + 1), index});

            this.onRcmdVisibleChange(false);
        }

        // let szFeatures = "top=0,";
        // szFeatures += "left=0,";
        // szFeatures += "width=" + (screen.availWidth - 10) + ",";
        // szFeatures += "height=" + (screen.availHeight - 60) + ",";
        // szFeatures += "directories=no,";
        // szFeatures += "status=yes,";
        // szFeatures += "menubar=no,";
        // szFeatures += "scrollbars=yes,";
        // szFeatures += "resizable=yes";
        // window.open(url, "", szFeatures);

        let {url = '', mobxrouteurl = '', target = 'mainFrame'} = obj;

        if (target != 'mainFrame' && url && url != 'javascript:void(0);') {
            window.open(url, target);
        } else {
            // 当路由地址不存在时，调用工具方法，解析单页地址中的路由地址
            if (!mobxrouteurl && url) {
                const urlObj = WeaTools.checkStdRouter(url) || {};
                if (urlObj.isRouter && urlObj.url) {
                    mobxrouteurl = urlObj.url;
                }
            }

            if (mobxrouteurl) {
                document.getElementById('contentFrame').style.visibility = 'hidden';
                document.getElementById('contentRoute').style.display = 'block';
                document.getElementById('mainFrame').src = 'about:blank';

                if (/^\/main/.test(mobxrouteurl)) {
                    weaHistory.push({pathname: mobxrouteurl});
                } else {
                    weaHistory.push({pathname: '/main' + mobxrouteurl});
                }
            } else if (url && url != 'javascript:void(0);') {
                weaHistory.push({pathname: '/main'});

                document.getElementById('mainFrame').src = url;
                document.getElementById('contentFrame').style.visibility = 'visible';
                document.getElementById('contentRoute').style.display = 'none';
            }
        }
    }

    onRcmdSearch(e) {
        const value = e.target.value;
        this.onRcmdVisibleChange(!!value);

        const {data} = this.state;
        const rcmdData = [];

        const loop = (moduleId, moduleName, item) => {
            const child = item.child;
            if (child && child.length) {
                for (let i = 0, len = child.length; i < len; i++) {
                    const {name = '', pinyin = ''} = child[i];
                    if (name.indexOf(value) != -1 || pinyin.indexOf(value.toLowerCase()) != -1) {
                        child[i].moduleId = moduleId;
                        child[i].moduleName = moduleName;
                        rcmdData.push(child[i]);
                    }
                    loop(moduleId, moduleName, child[i]);
                }
            }
        };

        data[0]['data'].forEach((item) => {
            const moduleId = item.infoId || '';
            const moduleName = item.name || '';

            const {name = '', pinyin = ''} = item;
            if (name.indexOf(value) != -1 || pinyin.indexOf(value.toLowerCase()) != -1) {
                item.moduleId = moduleId;
                item.moduleName = moduleId;
            }
            loop(moduleId, moduleName, item);
        });

        this.setState({rcmdData});
    }

    onRcmdVisibleChange(visible) {
        this.setState({rcmdVisible: visible});
    }
}

export default PortalMenu;